#!/usr/bin/python
# -*- coding: utf-8 -*-
#изготавливаем аплоадер.
import re,sys,optparse,urllib2,httplib
email='nanodesu@in-mail.ru'
passwd='splenchb'
username='nanodesu4'
album_id='7469727749'
host='avangard.photo.cod.ru'
USER_AGENT='Mozilla/5.0 (X11; U; Linux i686; ru-RU; rv:1.9) Gecko/2008062122 Minefield/3.0'

upload_album='http://avangard.photo.cod.ru/cabinet/upload/7469727749/'

#'http://avangard.photo.cod.ru/users/nanodesu4/7469727749/'

def auth_id_cod(user,passwd):
    cookes=str(urllib2.urlopen('https://id.cod.ru/auth?email=%s&password=%s' %(user,passwd)).info())
    cookes=re.findall('(codsid=.+?;)[\s\S\w\W]*(auth=YES;)[\s\S\w\W]*(modified=\d+?;)', cookes)[0]
    cookes='%s %s %s' %(cookes[0],cookes[1],cookes[2])
    return cookes


def encode_data(filename):
    def get_filedata(filename):
        f = open(filename);
        data = f.read()
        f.close()
        return data
    def get_content_type(file_name):
        cont_type=mimetypes.guess_type(file_name)[0] or 'application/octet-stream'
        return cont_type
    
    BOUNDARY='------------------------'
    L=[]
    L.append('--'+BOUNDARY)
    L.append('Content-Disposition: form-data; name="action"')
    L.append('')
    L.append('photo_upload')
    L.append('--'+BOUNDARY)
    L.append('Content-Disposition: form-data; name="album_id"')
    L.append('')
    #L.append('%s'%upload_album.split('/')[-2])
    L.append(album_id)
    L.append('--'+BOUNDARY)
    L.append('Content-Disposition: form-data; name="photos[]"; filename="%s"'%filename)
    L.append('Content-Type: image/jpeg')#%mimetypes.guess_type(filename)[0] or 'application/octet-stream' )
    #Content-Type: image/jpeg
    L.append('')
    #L.append(urllib2.urlopen('http://img2.putfile.com/thumb/11/31113245832.jpg').read())
    L.append(get_filedata(filename))
    L.append('--' + BOUNDARY + '--')
    L.append('')
    body = '\n'.join(L)
    content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
    return content_type,body
    
def upload_file(filename,cookie):
    content_type, body = encode_data(filename)
    header = httplib.HTTPConnection(host)
    header.putrequest('POST', '/upload/')
    header.putheader('User-Agent', USER_AGENT)
    header.putheader('Cookie',cookie)
    header.putheader('Content-Type', content_type)  
    header.putheader('Content-Length', str(len(body)))
    header.endheaders()
    header.send(body)
    #header.set_debuglevel(1)
    return header.getresponse()
def get_pages_urls(cookie,o):
    def get_pages(i,cookie):
        urlpage='http://avangard.photo.cod.ru/users/%s/%s/?page=%d' %(username,album_id,i)
        req = urllib2.Request(urlpage)
        req.add_header('Cookie', cookie)
        return urllib2.urlopen(req).read()  
    i=1
    url_data= get_pages(i,cookie)
    #urls = re.findall('(http://avangard.photo.cod.ru/photos.*/w100_.*)" alt=',url_data)
    i=re.findall('<td width="80%" align="center" class="f12">.*<b>(\d{1,})</b></td>',url_data)
    if i and not o:
        i=int(i[0])
        url_data= get_pages(i,cookie)
        urls = re.findall('(http://avangard.photo.cod.ru/photos.*/w100_.*)" alt=',url_data)
    elif i and o:
        i=int(i[0])
        urls=[]
        for i in range(o,i+1):
            url_data = get_pages(i,cookie)
            for url in re.findall('(http://avangard.photo.cod.ru/photos.*/w100_.*)" alt=',url_data):
                urls.append(url)
    elif not i:
        url_data= get_pages(1,cookie)
        urls = re.findall('(http://avangard.photo.cod.ru/photos.*/w100_.*)" alt=',url_data)
    print type(urls), len(urls)
    return urls,i
def output_urls(urls):
    out_url=[]
    for url in urls:
        tmb_100=url
        urlre=url.split('/w100_')
        tmb_400='%s/w400_%s'%(urlre[0],urlre[1])
        direct_url = '%s/%s'%(urlre[0],urlre[1])
        out_url.append((tmb_100,tmb_400,direct_url))
    print out_url
def main():   
    files = sys.argv[1:]
    cookie=auth_id_cod(email,passwd)
    old_urls, o= get_pages_urls(cookie, None)
    for file in files:
        if upload_file(file,cookie).status == 302: print 'OK'
        else: print 'error'
    new_urls, o=get_pages_urls(cookie, o)
    upload_urls = list( set(old_urls) ^ set(new_urls) )
    output_urls(upload_urls)
    
    

main()
